<?php
/**
 * Builds up a programmatic model for stacked SQL SET clauses to be used by INSERT query.
 * 
 * Note: MySQL uses this clause also for REPLACE
 */
class SQLInsertsClause extends AbstractSQLClause {
	public static function getInstance() {
		return new SQLInsertsClause();
	}
	
	private $tblColumns = array();
	
	/**
	 * Adds row to table
	 * 
	 * @example $objSQLUpdates = new SQLUpdatesClause(array("column1"=>new SQLValue("value1"),"column2"=>new SQLValue("value2"),...))
	 * @param SQLUpdatesClause $objSQLUpdates
	 * @return SQLInsertsClause
	 */
	public function addRow($objSQLUpdates) {
		$this->tblContents[]=$objSQLUpdates;
		return $this;
	}
	
	public function toString() { }
	
	/**
	 * Infers columns part @ SQL INSERT from rows added and returns them separated by string.
	 * 
	 * @example column1, column2, ...
	 * @return string
	 */
	public function getColumns() {
		$this->tblColumns = array();
		foreach($this->tblContents as $objSQLUpdates) {
			foreach($objSQLUpdates->toArray() as $strColumnName=>$mixValue) {
				$this->tblColumns[$strColumnName]=$strColumnName;	// this is to avoid incessant in_array
			}
		}
		return implode(",",$this->tblColumns);
	}
	
	/**
	 * Infers values part @ SQL INSERT from columns detected and rows added and returns them as string. If columns are specifically provided, it reorders values to
	 * reflect order set by that array.
	 * 
	 * @example ('value1','value2',...),...
	 * @param array $tblColumns
	 * @return string
	 */
	public function getRows($tblColumns = array()) {
		if(!sizeof($this->tblColumns)) $this->tblColumns = $tblColumns; 
		$output="";
		foreach($this->tblContents as $objSQLUpdates) {
			$tblUpdates = $objSQLUpdates->toArray();
			$output .= "(";
			foreach($this->tblColumns as $strColumnName) {
				$output .= $this->getValue(isset($tblUpdates[$strColumnName])?$tblUpdates[$strColumnName]:"''").", ";
			}
			$output =  substr($output, 0, -2)."), ";
		}
		return substr($output,0,-2);
	}
}